package main

import (
	"github.com/gin-gonic/gin"
	"fmt"
	"GinWebSocket/websocket"
	"net/http"
)

func main()  {
	wsHandler := new(websocket.WebSocketHandler)
	gin.SetMode(gin.DebugMode)
	r := gin.Default()
	r.GET("/websocket", func(c *gin.Context) {
		wsHandler.HandleConn(c.Writer,c.Request)
	})
	r.POST("/send", func(c *gin.Context) {
		key := c.PostForm("key")
		conn,err := websocket.GetWebSocketConn(key)
		if err != nil {
			c.JSON(http.StatusUnauthorized,gin.H{
				"error":err.Error(),
			})
			return
		}
		sv := c.PostForm("sendValue")
		err = websocket.SendMsgToClient(conn,[]byte(sv))
		if err != nil {
			c.JSON(http.StatusBadRequest,gin.H{
				"error":err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK,gin.H{
			"msg":"ok",
			"sendValue":sv,
		})
	})
	err := r.Run(":8888")
	if err != nil {
		fmt.Println(err)
	}
}
